// Export selectors engine
var $$ = Dom7;

(function($) {
	'use strict';
	$$.maoutil = {
			formatNumber:function(num,decimal){
				decimal = decimal > 0 && decimal <= 20 ? decimal : 2;   
				num = parseFloat((num + "").replace(/[^\d\.-]/g, "")).toFixed(decimal) + "";
				var l = num.split(".")[0].split("").reverse(),
				r = num.split(".")[1];
				var t = "";
				for(var i = 0; i < l.length; i ++ ) {
				      t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? "," : "");
				}
				return t.split("").reverse().join("") + "." + r;
			},
			extend:function(target){
				var sources = [].slice.call(arguments,1);
				for (var i in sources){
					var source = sources[i];
					for(var key in source){
						target[key] = source[key];
					}
				}
				return target;
			}
	};
	Template7.registerHelper("url",function(){
		  var params = [];
		  for (var i = 0;i<arguments.length - 1;i++){
			  params.push(arguments[i]);
		  }
		  return $$.config.base+params.join("");
	});
	Template7.registerHelper("imgurl",function(v,op){
		var w = op.hash.w,h=op.hash.h;
		if (w && h){
			v = v+"@"+w+"w_"+h+"h_1c_1e";
		} else if (w){
			v = v+"@"+w+"w";
		} else if (h != 0){
			v = v+"@"+h+"h";
		}
		return $$.config.image+v;
	});
	Template7.registerHelper("multi",function(v1,v2){
		  return v1 * v2;
	});
	
	Template7.registerHelper("fnumber",function(num,decimal){
		return $$.maoutil.formatNumber(num,decimal);
	});
	Template7.registerHelper("mfnumber",function(num1,num2,decimal){
		  return $$.maoutil.formatNumber(num1 * num2,decimal);
	});
	//平屏蔽
})(window);
(function(){
	$$.cookie = {
	    get: function(name) {
	      var cookieName = encodeURIComponent(name) + '=';
	      var cookieStart = document.cookie.indexOf(cookieName);
	      var cookieValue = null;
	      var cookieEnd;
	
	      if (cookieStart > -1) {
	        cookieEnd = document.cookie.indexOf(';', cookieStart);
	        if (cookieEnd == -1) {
	          cookieEnd = document.cookie.length;
	        }
	        cookieValue = decodeURIComponent(document.cookie.substring(
	          cookieStart +
	          cookieName.length, cookieEnd));
	      }
	
	      return cookieValue;
	    },
	
	    set: function(name, value, expires, path, domain, secure) {
	      var cookieText = encodeURIComponent(name) + '=' +
	        encodeURIComponent(value);
	
	      if (expires instanceof Date) {
	        cookieText += '; expires=' + expires.toGMTString();
	      }
	
	      if (path) {
	        cookieText += '; path=' + path;
	      }
	
	      if (domain) {
	        cookieText += '; domain=' + domain;
	      }
	
	      if (secure) {
	        cookieText += '; secure';
	      }
	
	      document.cookie = cookieText;
	    },
	
	    unset: function(name, path, domain, secure) {
	      this.set(name, '', new Date(0), path, domain, secure);
	    }
	};
	
  var CART_NAME = "cart.maggiemaostudio";
  var domain = window.document.domain;
  if (domain.indexOf("localhost") >=0){
	  domain = "";
  }
  $$.cart = {
	  add:function(product){
		  var list = this.list();
		  product["quantity"] = 1;
		  //{id,name,enname,image,fullImage,size,color,quantity,price}
		  var exist = this.match(product,list);
		  if (exist){
			  exist.quantity++;
			  this.store(list);
			  this.trigger("add", product);
		  } else {
			  list.push(product);
			  this.store(list);
			  this.trigger("add", product);
		  }
		  return list;
	  },
	  increment:function(product){
		  var list = this.list();
		  var exist = this.match(product,list);
		  if (exist){
			  exist.quantity++;
			  this.store(list);
			  this.trigger("increment", product);
		  }
		  return list;
	  },
	  decrement:function(product){
		  var list = this.list();
		  var exist = this.match(product,list);
		  if (exist){
			  if (exist.quantity == 1){
				  this.destroy(product,list);
			  } else {
				  exist.quantity--;
				  this.store(list);
				  this.trigger("decrement", product);
				  
			  }
		  }
		  return list;
	  },
	  destroy:function(product,products){
		  var list = products || this.list();
		  //var exist = this.match(product.id,list);
		  for (var i in list){
			  if (this.eq(product,list[i])){
				  //delete list[i];
				  list.splice(i,1);
				  this.store(list);
				  this.trigger("destroy", product);
				  break;
			  }
		  }
		  return list;
	  },
	  destroyAll:function(){
		  //name, path, domain, secure)
		  $$.cookie.unset(CART_NAME,'/',domain,false);
	  },
	  trigger:function(event,params){
		  $$(window).trigger(event+".cart.maggiemaostudio",params);
	  },
	  match:function(product,list){
		  for (var i in list){
			  if (this.eq(product, list[i])){
				  return list[i];
			  }
		  }
	  },
	  eq:function(p1,p2){
		  function equals(v1,v2){
			  //验证是否都有值或者
			  if (!!v1 === false && !!v2 === false){
				  //空值("",undefined,null)
				  return true
			  } else  if (!!v1 === true && !!v2 === true && v1 == v2){
				  //有值
				  return true;
			  } else {
				  return false;
			  }
		  }
		  return equals(p1.id,p2.id) && equals(p1.size_id,p2.size_id) && equals(p1.color_id,p2.color_id);
	  },
	  get:function(product){
		  var list = this.list();
		  return this.match(product,list);
	  },
	  list:function(){
		  var value = $$.cookie.get(CART_NAME)
		  if (!value){
			  return [];
		  }
		  return JSON.parse(value);
	  },
	  store:function(products){
		  var value = JSON.stringify(products);
		  var days = 30;
		  var exp = new Date(); 
		  exp.setTime(exp.getTime() + days*24*60*60*1000);
		  if (domain){
			  //,domain,false
			  $$.cookie.set(CART_NAME, value, exp, "/",domain,false);
		  } else {
			  $$.cookie.set(CART_NAME, value, exp, "/");
		  }
	  }
	};
})();


var Pages = {
		'page-product-list':function(app,page){
			// 注册'infinite'事件处理函数
    		var loading = false;
    		var page = 1;
    		 // Attach 'infinite' event handler
    		var loc = window.location;
    		var url = "http://" + loc.host + loc.pathname;
    	    $$('.infinite-scroll').on('infinite', function () {
    	        // Exit, if loading in progress
    	        if (loading) return;
    	        // Set loading trigger
    	        loading = true;
    	        // Request some file with data
    	        page++;
    	        var pages = $$(this).data("pages");
    	        if (pages >= page){
    	        	 $$.get(url, {page: page}, function (data) {
    	    	            loading = false;
    	    	            var $views;
    	    	            var $data = $$(data);
    	    	            $data.each(function(i,e){
    	    	            	if ($$(e).is(".views")){
    	    	            		$data = $$(e);
    	    	            	}
    	    	            });
    	    	            var $cols = $data.find(".col-100");
    	    	            if ($cols.length == 0) {
    	    	                // Nothing more to load, detach infinite scroll events to prevent unnecessary loadings
    	    	            	app.detachInfiniteScroll($$('.infinite-scroll'));
    	    	            }
    	    	            else {
    	    	                // Append loaded elements to list block
    	    	            	$$('.infinite-scroll .row').append($cols);
    	    	            }
    	    	        });
    	        } else {
    	        	app.detachInfiniteScroll($$('.infinite-scroll'));
    	        }
    	    });
		},
		'page-product':function(app,page){
			//初始化下拉框
    		$$('select.cs-select').each(function(i,e){
    			var name = 'size';
    			if (e.name == 'color_id'){
    				name = 'color';
    			}
    			new SelectFx(e,{text:name});
    		});
    		
    		//绑定添加商品事件
    		//添加商品按钮
    		$$(document).on('click', '#add-product:not(.disable)', function (e) {
    			var product = app.formToJSON("#product-form");
    			//alert(JSON.stringify(product));
    			if (product.size_id == 0){
    				app.alert("请选择尺寸");
    				return;
    			}
    			if (product.color_id == 0){
    				app.alert("请选择颜色");
    				return;
    			}
    			$$.cart.add(product);
    			//app.alert("已成功加入购物车");
    			window.location.href = $$.config.base + 'cart';
    		});
    		
    		//增加收藏夹
  		   $$(document).on("click","#add-favorite",function(){
  			  if (!$$.config.login){
  				  mainView.router.load({pageName: 'page-login'});
  				  return;
  			  }
  			  var product = app.formToJSON("#product-form");
			  if (product.size_id == 0){
				  app.alert("请选择尺寸");
				  return;
			  }
			  if (product.color_id == 0){
				  app.alert("请选择颜色");
				  return;
			  }
			  //提交请求
			  $$.post($$.config.base+"product/favorite",product,function(data){
				  app.alert("收藏成功");
			  });
  		  });
		},
		'page-cart':function(app,page){
			var products = $$.cart.list();
    		function calcFee(products){
    			var fee = {
    					productsFee:0,
    					postage:0,
    					totalFee:0
    			};
    			var freeFreight = false;
    			$$.each(products,function(i,e){
    				fee.productsFee += e.quantity * e.price;
    				if (e.postage_mode == 2){
    					freeFreight = true;
    				}
    			});
    			if (fee.productsFee < $$.config.freePostageLimit && !freeFreight){
    				fee.postage = $$.config.postage;
    			} 
    			
    			fee.totalFee = fee.productsFee + fee.postage;
    			
    			return fee;
    		}
    		function refreshFee(products){
    			var fee = calcFee(products);
    			$$("#products-fee").text($$.maoutil.formatNumber(fee.productsFee, 2));
    			$$("#postage").text($$.maoutil.formatNumber(fee.postage, 2));
    			$$("#total-fee").text($$.maoutil.formatNumber(fee.totalFee, 2));
    		}
    		var data = {products:products,fee:calcFee(products)};
    		var cartHTML = Template7.templates.cartTemplate(data);
    		$$(".m-cart-list").html(cartHTML);
    		
    		//初始化删除产品
    		$$(".m-cart-list").on("click",".delete",function(e){
    			e.preventDefault();
    			var $item = $$(this).parents("li");
    			app.confirm("确定删除吗？", function(){
	    			var product = $$($item).dataset();
	    			var products = $$.cart.destroy(product);
	    			$item.remove();
	    			refreshFee(products);
    			});
    		});
    		
    		//初始化增加产品数量
    		$$(".m-cart-list").on("click",".plus",function(e){
    			e.preventDefault();
    			var $item = $$(this).parents("li");
    			var product = $$($item).dataset();
    			//product.quantity += 1;
    			var quantity = product.quantity;
    			var products = $$.cart.increment(product);
    			quantity++;
    			refreshFee(products);
    			$$($item).attr("data-quantity",quantity);
    			$$($item).find(".quantity").text(quantity);
    			$$($item).find(".product-fee").text($$.maoutil.formatNumber(quantity * product.price, 2));
    		});
    		//初始化增加产品数量
    		$$(".m-cart-list").on("click",".minus",function(e){
    			e.preventDefault();
    			var $item = $$(this).parents("li");
    			var product = $$($item).dataset();
    			if (product.quantity == 1){
    				return;
    			}
    			var quantity = product.quantity;
    			var products = $$.cart.decrement(product);
    			quantity--;
    			refreshFee(products);
    			$$($item).attr("data-quantity",quantity);
    			$$($item).find(".quantity").text(quantity);
    			$$($item).find(".product-fee").text($$.maoutil.formatNumber(quantity * product.price, 2));
    			
    		});
    		
    		$$("#submit-cart").click(function(){
    			var list = $$.cart.list();
    			if (list.length == 0){
    				app.alert("购物车没有商品");
    				return;
    			}
    			if (!$$.config.login){
    				mainView.router.load({pageName: 'page-login'});
    				return;
    			}
    			
    			//检查库存是否足够
    			$$.post($$(this).data("url"),function(str){
    				var data = JSON.parse(str);
    				if (data.success){
    					$$("#order-from").submit();
    				} else {
    					if (data.error_no == "1" || data.error_no == 1){
    						var errors = data.errors;
    						$$.each(errors,function(i,e){
    							var $li;
    							if (e.size_id){
    								$li = $$("#product"+e.product_id+"-"+e.size_id+"-");
    							} else if (e.color_id){
    								$li = $$("#product"+e.product_id+"--"+e.color_id);
    							} else {
    								$li = $$("#product"+e.product_id+"--");
    							}
    							//$li.find(".unenough").show();
    							$li.find(".unenough").text("当前库存量"+e.current_quantity);
    						});
    					}
    				}
    			});
    		});
		},
		'page-order-form':function(app,page){
			Pages["page-cart"].call(app,app,page);
			
			/**
			 * 地址选择
			 */
			$$(document).on("click",".address-checkbox",function(){
				if ($$("#update-address-button").hasClass("hidden")){
					$$("#update-address-button").removeClass("hidden");
				}
			})
			/**
			 * 卡片选择
			 */
			$$(document).on("click",".card-checkbox",function(){
				if ($$(this).hasClass("yes")){
					$$("#card-content-wrap").removeClass("hidden");
				} else {
					$$("#card-content-wrap").addClass("hidden");
				}
			})
			//表单验证
			$$("#order-form").on("submit",function(){
				var valid = true;
				//必须要有产品
				if ($$.cart.list().length == 0){
					app.alert("没有选择商品");
					valid = false;
				}
				var order = app.formToJSON($$(this));
				//必须选择地址
				if (!order.user_address_id){
					app.alert("请选择订单地址");
					valid = false;
				}
				//检查卡片内容
				if (order.card_type == 3){
					if (!$$.form.maxLength(order.card_content, 100)){
						app.alert("卡片内容必须填写，并且在100个字符内。");
						valid = false;
					}
				}
				//检查留言是否超出100
				if (!$$.form.maxLength(order.leave_message, 100, false)){
					app.alert("留言不能超过100个字符。");
					valid = false;
				}
				if (!valid){
					event.preventDefault();
		        	event.stopPropagation();
		            return false 
				}
			});
			//地址新增
			$$("a.add-address").on("click",function(){
				mainView.router.load({pageName: 'page-add-address'});
				$$(document).trigger("add.address");
			});
			
			//更新地址
			$$("a.update-address").on("click",function(){
				mainView.router.load({pageName: 'page-add-address'});
				var order = app.formToJSON("#order-form");
				var $address = $$("#address-checkbox-" + order.user_address_id);
				var address = $address.data("dataset");
				if (!address){
					address = $address.dataset();
				}
				$$(document).trigger("update.address",address);
			});
		},
		'page-add-address':function(app,page){
			function fillSelect(sel,data,selectedId){
				var options = [];
				var selectIndex = 0;
				$$.each(data,function(i,e){
					if (e.id == selectedId){
						selectIndex = i;
						options.push("<option value='"+e.id+"' selected>"+e.name+"</option>");
					} else {
						options.push("<option value='"+e.id+"' >"+e.name+"</option>");
					}
					
				});
				$$(sel.el).html(options.join(""));
				sel.reinit();
			}
			
			function changeProvince(){
				//var $item = $$('#province_id').find("option[selected]");
				//var id = $item.data("id")
				var id = $$("#province_id").val();
				$$.get($$.config.base + "user/address/cities/"+id,function(data){
					data = JSON.parse(data);
					fillSelect(citySel,data['cities']);
					fillSelect(districtSel,data['districts']);
				});
			}
			
			
			function changeCity(){
				var id = $$('#city_id').val();
				$$.get($$.config.base + "user/address/districts/"+id,function(data){
					data = JSON.parse(data);
					fillSelect(districtSel,data);
				});
			}
			
			function fillProvinces(address,successFn){
				var params = "";
				if (address){
					params = "?pid="+address.province_id+"&cid="+address.city_id;
				}
				$$.get($$.config.base +"user/address/provinces"+params,function(data){
					data = JSON.parse(data);
					
					fillSelect(provinceSel,data['provinces'],address && address.province_id);
					fillSelect(citySel,data['cities'],address && address.city_id);
					fillSelect(districtSel,data['districts'],address && address.district_id);
					if (successFn){
						successFn();
					}
				});
			}
			
			var provinceSel = new SelectFx($$("#province_id")[0],{
				onChange:changeProvince,
			});
			var citySel = new SelectFx($$("#city_id")[0],{
				onChange:changeCity
			});
			
			var districtSel = new SelectFx($$("#district_id")[0]);
			var addAddress = true;
			
			$$(document).on('add.address',function(e){
				$$("#add-address-form").removeClass("update").addClass("add");
				$$("#address-id").remove();
				//清空表单数据
				$$("#add-address-form").find("#name").val('');
				$$("#add-address-form").find("#mobile").val('');
				$$("#add-address-form").find("#zipcode").val('');
				$$("#add-address-form").find("#street").val('');
				fillProvinces();
			});
			
			$$(document).on('update.address',function(e){
				var address = e.detail;
				$$("#add-address-form").removeClass("add").addClass("update");
				fillProvinces(address,function(){
					app.formFromJSON("#add-address-form",address);
					$$("#add-address-form").append("<input id='address-id' type='hidden' name='id' value="+address.id+" />");
				});
			});
			
			//表单验证
			$$.form.validate($$(page.container).find("form"));
		},
		'page-userinfo':function(app,page){
			//表单验证
			$$.form.validate($$(page.container).find("form"));
		},
		'page-address-list':function(app,page){
			//地址新增
			$$("a.add-address").on("click",function(){
				mainView.router.load({pageName: 'page-add-address'});
				$$(document).trigger("add.address");
			});
			
			//更新地址
			$$(document).on("click","a.update-address",function(){
				mainView.router.load({pageName: 'page-add-address'});
				var order = app.formToJSON("#order-form");
				var $address = $$(this).parents("li");
				var address = $address.data("dataset");
				if (!address){
					address = $address.dataset();
				}
				$$(document).trigger("update.address",address);
			});
			
			$$(document).on("click","a.delete-address",function(){
				var $address = $$(this).parents("li");
				var data = $address.dataset();
				app.confirm("确定删除吗？", function(){
					$$.post($$.config.base + "user/address/delete",{id:data.id},function(result){
						var data = JSON.parse(result);
						if (data.success){
							$address.remove();
						} else {
							app.alert("删除失败，请稍后重试!");
						}
					});
				});
			});
		},
		'page-favorite-list' : function(app,page){
			$$(document).on("click","span.delete",function(e){
				e.preventDefault();
				var $f = $$(this).parents('li');
				app.confirm("确定删除吗？", function(){
					var data = $f.dataset();
					$$.post($$.config.base + "user/favorite/delete",{id:data.favorite_id},function(result){
						var data = JSON.parse(result);
						if (data.success){
							$f.remove();
							if ($$("#favorite-list ul li").length == 0){
								$$("#favorite-list").addClass("no-border");
							}
						} else {
							app.alert("删除失败，请稍后重试!");
						}
					});
				});
				
			});
			
			$$(document).on("click","button.cart-button",function(e){
				e.preventDefault();
				if ($$(this).hasClass("disable")){
					return;
				}
				var $f = $$(this).parents("li");
				var data = $f.dataset();
				if (!$$.form.required(data.size_id)){
					delete data["size_id"];
					delete data["size"];
				}
				if (!$$.form.required(data.color_id)){
					delete data["color_id"];
					delete data["color"];
				}
				$$.cart.add(data);
				app.alert("已成功加入购物车");
				
			});
		},
		'page-story':function(app,page){
			$$(page.container).find(".m-story-content a").addClass("external");
			var swiper = $$('.swiper-container')[0].swiper;
			$$(".swiper-container").find(".swiper-slide").each(function(i,e){
				if ($$(e).hasClass('active')){
					if (i == 0){
						swiper.slideTo(1);
						swiper.slideTo(0);
					}else {
						swiper.slideTo(i);
					}
				}
			});
		},
		'page-order-pay':function(app,page){
			var submitting = false;
			$$("#pay-button").on("click",function(){
				
				if (submitting) {
					return;
				}
				submitting = true;
				var url = $$(this).data("url");
				if (wxparams){
					if( typeof WeixinJSBridge === 'undefined' ) {
				        app.alert('请在微信在打开页面！');
				        return false;
				    }
				    WeixinJSBridge.invoke(
				        'getBrandWCPayRequest',wxparams, function(res) {
				        switch(res.err_msg) {
				            case 'get_brand_wcpay_request:cancel':
				                //alert('用户取消支付！');
				            	submitting = false;
				                break;
				            case 'get_brand_wcpay_request:fail':
				                app.alert('支付失败！（'+res.err_desc+'）');
				                submitting = false;
				                break;
				            case 'get_brand_wcpay_request:ok':
				                //alert('支付成功！');
				                window.location.href=url;
				                break;
				            default:
				            	submitting = false;
				                app.alert(JSON.stringify(res));
				                break;
				        }
				    });
				} else {
					$$(this).parent("form").submit();
				}
			});
		},
		'page-user':function(app,page){
			$$("#unbind").on("click",function(e){
				var $this = $$(this);
				//提交请求
				if ($this.hasClass("unbinded")){
					return;
				}
				$$.post($$.config.base+"user/unbind",{},function(data){
					var ret = JSON.parse(data);
					if (ret.success){
						$this.addClass("unbinded");
						app.alert("解绑成功");
					} else {
						app.alert("解绑失败");
					}
				});
			});
		}
}

var FormSubmited = {
		'login-form':{
			success:function(data){
				if (data.intended){
					window.location.href=data.intended;
				} else {
					window.location.reload();
				}
			}
		},
		'forgot-form':{
			success:function(data){
				//打开成功page
	    		mainView.router.load({pageName: 'page-forgot-success'});
			}
		},
		'register-form':{
			success:function(data){
				//打开成功page
	    		mainView.router.load({pageName: 'page-register-success'});
			}
		},
		'order-form':{
			success:function(data){
				if (data.success){
					//删除商品cookie信息
	            	$$.cart.destroyAll();
	            	window.location.href = $$.config.base+"order/pay/"+data.order_id;
				} else {
					app.alert("订单失败，可能库存不足!");
				}
				
			}
		},
		'add-address-form' : {
			success:function(data){
				if ($$(this).hasClass('add')){
					var cartHTML = Template7.templates.addressTemplate(data);
		    		$$("#address-list").append(cartHTML);
					//附加一条地址信息
				} else if ($$(this).hasClass('update')){
					//同步内容
					var $address = $$("#address-checkbox-"+data.id);
					$address.find(".name").text(data.name);
					$address.find(".address").text(data.province +" " + (data.city+data.district+data.street));
					$address.find(".mobile").text(data.mobile);
					$address.data("dataset",data);
				}
				//mainView.router.load({pageName: 'page-order-form'});
				mainView.router.back();
				
			}
		},
		'update-userinfo-form': {
			success : function(data){
				myApp.alert("保存成功");
			}
		}
}

//Initialize your app
var myApp = new Framework7({
	init:false,
	modalTitle:"",
	modalButtonOk:'确定',
	modalButtonCancel:'取消',
	precompileTemplates: true,
	// Hide and show indicator during ajax requests
    onPageInit:function(app,page){
    	if (page.name == "page-login" || page.name == "page-forgot" || page.name=='page-reset-password' || page.name=='page-register'){
    		//增加表单验证
    		
    		if (page.name=="page-forgot"){
    			$$("#forget-verify-input button").phoneVerifyCode({
    				phone:"#forget-moible-input input",
    				form:"#forget-form"
    			});
    		} else if (page.name == "page-register"){
    			$$("#register-verify-input button").phoneVerifyCode({
    				phone:"#forget-mobile-input input",
    				form:"#forget-form"
    			});
    		}
    		$$.form.validate($$(page.container).find("form"));
    	} else if (page.name == 'page-forgot-success' || page.name == 'page-register-success'){
    		$$(page.container).find(".back-main").on("click",function(){
    			var mainPage = mainView.history[0];
    			mainPageName = mainPage.substring(1);
				mainView.router.back({"pageName":mainPageName,"force":true});
			});
    	}else{
    		if (page.name != 'navbar' && page.name != 'page-index'){
    			if (typeof(Pages[page.name]) == 'function'){
    				Pages[page.name].call(app,app,page);
    			}
    		}
    	}
    	
    	if ($$.config.showLogin == "1"){
			  mainView.router.load({pageName: 'page-login'});
		}
    }
});
//Show/hide preloader for remote ajax loaded pages
//Probably should be removed on a production/local app
$$(document).on('ajaxStart', function (e) {
 myApp.showIndicator();
});
$$(document).on('ajaxComplete', function () {
 myApp.hideIndicator();
});
//Add view

var mainView = myApp.addView('.view-main', {
    // Because we use fixed-through navbar we can enable dynamic navbar
	domCache: true, //enable inline pages
});

/**
 * 登录的表单控制
 */
$$('form.ajax-submit').on('submitted', function (e) {
	var xhr = e.detail.xhr; // actual XHR object
	var formName = $$(this).attr("name");
	var handle = FormSubmited[formName];
	
	if (handle){
		var dataType = handle.dataType;
		if (dataType == undefined || dataType == 'json'){
			var data = JSON.parse(e.detail.data);
			var callback = handle.callback;
			if (callback){
				callback.call(this,data);
			} else {
				//成功
			    if (data.success){
			    	//刷新当前页面
			    	handle.success.call(this,data);
			    } else {
			    	var error = handle.error;
			    	if (error){
			    		error.call(this,data);
			    	} else {
			    		if (data.errors){
			    			var msgs = [];
			    			for (var key in data.errors){
				    			msgs.push(data.errors[key]);
				    		}
			    			myApp.alert(msgs.join("<br>"));
			    		} else {
			    			myApp.alert(data.error);
			    		}
			    		//{"success":false,"errors":{"zipcode":["%s\u4e0d\u80fd\u4e3a\u7a7a"]}}
			    	}
			    }
			}
		}
	}
});

$$.user = {
  check:function(){
	  var $$action = $$("#user-start-action");
	  //登录，增加跳转到用户页面的按钮
	  if ($$.config.login){
		  $$action.addClass("external");
		  $$action.attr("href",$$.config.base+"user").text($$.config.user);//跳转到用户页面
		  //$(".m-nav-user").html("<a href='"+$.config.base+"user'><span id='user' class='m-login-user-btn'>" + $.config.user+"</span></a><a href= '"+$.config.base+"logout'><span class='m-logout-btn'>退出</span></a>");
	  } else {
		  $$action.attr("href","#page-login");
	  }
  },
  renderCartSize:function(){
	  var list = $$.cart.list();
	  var size = 0;
	  $$.each(list,function(i,p){
		 size += p.quantity; 
	  });
	  $$("#cart-size").text(size);
	  if (list.length > 0){
		  $$("#cart-action").attr("href",$$.config.base + 'cart');
	  }else {
		  //$$("#cart-action").attr("href","#");
		  $$("#cart-action").attr("href",$$.config.base + 'cart');
	  }
  }
}

$$.form = {
		validate:function($form,successFn,errorFn){
			// Checks if instance is already created 
	        if ( $form.data("instance") ) {
	          return;
	        }
	        var temp=[]
	        $form.find(".validate").each(function (i, el) {
	          var $el = $$(el)
	          temp.push({name: $el.attr("name"), 
	                     rules: $el.attr("data-rules"),
	                     display: $el.attr("data-display")
	                   })
	        });
	        // Create FormValidator object
	        var validator = new FormValidator($form.attr('name'), temp, function(errors, event) {
	          // Check for errors 
	          if(errors.length > 0) {
	        	  if (errorFn){
	        		  errorFn($form,errors,event);
	          	  } else {
	          		var errMsgs = [];
	          		$$.each(errors,function(i,e){
	          			errMsgs.push(e.message);
	          		});
	          		myApp.alert(errMsgs.join("<br>"));
	          	  }
	        	 event.preventDefault();
	        	 event.stopPropagation();
	        	 //event.cancelBubble=true;
	        	 //event.returnValue = false;
	             return false 
	          } else {
	            if (successFn) {
	            	return success ($form, event ); //execute callback on form success
	            }
	          }
	        });
	        $form.data("instance", validator);
	        return validator;
		},
		required: function(value) {
			if (!value){
				return false;
			}
			if (value == "0" || value==""){
				return false;
			}
			return true;
		},
		maxLength: function(value, length,required) {
			//检查是否为空值
			if (!this.required(value)){
				//如果是空值,则看是否要求必须填写
				if (required == false){
					return true;
				} else {
					return false;
				}
			}
            return (value.length <= length);
        },
}



$$(window).on("load",function(){
	myApp.init();
	//检测用户是否登录
	$$.user.check();
	$$.user.renderCartSize();
	$$(window).on("destroy.cart.maggiemaostudio",function(e,data){
		  $$.user.renderCartSize();
	});
	$$(window).on("add.cart.maggiemaostudio",function(e,data){
		  $$.user.renderCartSize();
	});
});


(function($){
//	var cookieHelper = $.AMUI.utils.cookie;
	var cookieKey = "$$____-seconds_remained";
	var cookies = {
			set:function(value,seconds){
				  var exp = new Date(); 
				  exp.setTime(exp.getTime() + seconds * 1000);
				  $$.cookie.set(cookieKey, value, exp, "/");
			},
			get:function(){
				return $$.cookie.get(cookieKey);
			}
	}
	
	
	
	var cookieKey = "$$____-seconds_remained";
	
	var PhoneVerifyCode = function(target,options){
		var defaults = {
				phone:"",
				form:"",
				action:$.config.base+"verify-code",
				keeper:90,
				error:"",
				target:"",
		}
		this.options = $.maoutil.extend({},defaults,options);
		this.target = target;
		var that = this;
//		this.target = $(this.options.target);
		this.target.click(function(){
			if (that.verify()){
				that.post();
			}
		});
		var v = cookies.get();//获取cookie值
	    if(v>0){
	        this.countDown();//开始倒计时
	    }
	}
	
	PhoneVerifyCode.prototype = {
			verify:function(){
				var phonenum = this.getPhoneNum();
			    var myreg = /^1[34578]\d{9}$/; 
			    if(!myreg.test(phonenum)){ 
			        myApp.alert("请输入有效的手机号码！");
			        return false; 
			    }else{
			        return true;
			    }
			},
			getPhoneNum:function(){
				return $(this.options.phone).val();
			},
			post:function(target){
				
//				this.target = target;
				var mobile = this.getPhoneNum();
				var that = this;
//				var token = $(this.options.form).find("[name='_token']").val();
				var token = $(this.options.form).find("[name='_token']").val();
				$.post(this.options.action,{mobile:mobile,'_token':token},function(result){
				});
				cookies.set(90,90);//添加cookie记录,有效时间90s
				that.countDown();
			},
			countDown:function(){
				this.countValue = cookies.get();
				
			    if (!this.countValue) { 
			        this.target.removeAttr("disabled");    
			        this.target.text("获取验证码"); 
			        return;
			    } else { 
			    	 this.target.attr("disabled", true); 
			    	 this.target.text("重新发送(" + this.countValue + ")"); 
			    	 this.countValue--;
			    	 cookies.set(this.countValue,this.countValue + 1);
			    } 
			    var that = this;
			    setTimeout(function(){
			    	that.countDown();
			    },1000);
			}
	};
	
	$.fn.phoneVerifyCode = function(options){
		var key = "plugin-phone-verify-code";
		var plugin = $(this).data(key);
		if (!plugin){
			plugin = new PhoneVerifyCode(this,options);
			$(this).data(key,plugin);
		}
		return plugin;
		
	};
})($$);
